#!/bin/bash
echo "用途: 标准彩食鲜项目脚手架生成脚本"
echo "使用命令格式:"
echo "curl -O https://gitee.com/yhcsx/csx-bsf-demo/raw/{version}/doc/client.sh"
echo "sh client.sh {projectName} {groupId} {package} {version}"
## projectName is the artifcactId of Project
projectName=$1
groupId=$2
package=$3
version=$4 #默认master
if [[ $projectName == "" ]]; then
	echo "错误: 请输入新项目名"
	exit 0
fi
if [[ $groupId == "" ]]; then
	echo "错误: 请输入groupId"
	exit 0
fi
if [[ $package == "" ]]; then
	echo "错误: 请输入package"
	exit 0
fi
if [[ $version == "" ]]; then
	version="master"
fi

### 目录
path=$(cd $(dirname $0); pwd)
projectPath=$path/$projectName
echo "当前目录:$path,新项目名:$projectName,groupID:$groupId (例如：com.yh.csx),脚手架版本:$version"


### 下载项目模板
rm -rf csx-b2b-demo-${version}.tar.gz
response=$(curl -o csx-bsf-demo-${version}.tar.gz -O https://gitee.com/yhcsx/csx-bsf-demo/repository/archive/master?ref=master&format=tar.gz \
        --max-time 3600 \
        --time-cond \
        --connect-timeout 3600 \
        --write-out %{http_code} \
        --silent \
)

if [ -d "$projectPath" ];then
  echo ‘删除文件’
  rm -Rf $projectPath
fi
#tar -zxvf csx-bsf-demo-${version}.tar.gz
unzip csx-bsf-demo-${version}.tar.gz
mv -fiv $path/csx-bsf-demo $projectPath
echo "下载模板完毕:csx-bsf-demo-${version}.tar.gz"

###循环所有文件 替换com.yh.csx.demo
function loopdic(){
  for f in `ls $1`
  do
    if [ -d $1"/"$f ];then
      loopdic $1"/"$f
    else
      local path2=$1"/"$f 
      local name2=$f
	  #if [[ $path2 == *client.sh ]]; then echo '打印$path2' ;fi
	  if [[ ($path2 == *.java) || ($path2 == *.xml) || ($path2 == *.properties) || ($path2 == *.md) ]]; then   
		 echo "扫描文件: ${path2}"
		  sed -i "s/com.yh.csx.demo/$package/g" $path2		  
  		  sed -i "s/\<com.yh.csx\>/\<$groupId\>/g" $path2 
		  sed -i "s/csx-bsf-demo/$projectName/g" $path2 
		  sed -i "s/swagger.title=DEMO/swagger.title=$projectname/g" $path2
	  fi
    fi
  done
}
loopdic $projectPath
echo "完毕:循环所有文件并替换demo信息"

### 循环替换模块文件夹
dirs=('csx-bsf-demo-core' 'csx-bsf-demo-provider' 'csx-bsf-demo-dao' 'csx-bsf-demo-service' 'csx-bsf-demo-api' 'csx-bsf-demo-task')
packagedir=${groupId//\./\/};
for d in ${dirs[@]}
do
    newd=${d/csx-bsf-demo/${projectName}}
    echo "扫描文件夹: $projectPath/$d/"
    if [ ! -d "$projectPath/$d/src/main/java/$packagedir/" ];then
       echo ‘删除文件’
       mkdir -p $projectPath/$d/src/main/java/$packagedir/
    fi
    mv -fiv $projectPath/$d/src/main/java/com/yh/csx/demo $projectPath/$d/src/main/java/$packagedir
    rm -Rf $projectPath/$d/src/main/java/com/yh/
    mv -fiv $projectPath/$d $projectPath/$newd
done
echo "完毕:循环模块文件夹重命名所有demo目录"
echo "全部完成！！！享受它把~~~~"
echo "by 车江毅&王志斌"
